package cn.haohaowo.service.impl;

import cn.haohaowo.common.Constants;
import cn.haohaowo.entity.Account;
import cn.haohaowo.service.AccountBizService;
import cn.haohaowo.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Service
public class AccountBizServiceImpl implements AccountBizService {

	@Autowired(required = false)
	private RestTemplate restTemplate;

	public boolean emailExist(Integer accountId, String email) {

		String url = Constants.RESTFUL_URL + "account/queryEmailExist";
		MultiValueMap<String, Object> para = new LinkedMultiValueMap<>();
		para.set("accountId", accountId);
		para.set("email", email);
		String result = restTemplate.postForObject(url, para, String.class);
		JSONObject jsonObject;
		if (StringUtils.isNotEmpty(result)) {
			jsonObject = JSONObject.parseObject(result);
			Boolean isExist = jsonObject.getBoolean("isExist");
			return isExist;
		}

		return false;

	}

	public Account login(String userName, String password) {

		String url = Constants.RESTFUL_URL + "account/queryAccount";
		MultiValueMap<String, Object> para = new LinkedMultiValueMap<>();
		para.set("userName", userName);
		para.set("password", password);
		String result = restTemplate.postForObject(url, para, String.class);
		if (StringUtils.isNotEmpty(result)) {
			Account account = JSONObject.parseObject(result, Account.class);
			return account;
		}

		return null;

	}

	public boolean saveOrUpdateAccount(Account account) {

		String url = Constants.RESTFUL_URL + "account/saveOrUpdateAccount";
		MultiValueMap<String, Object> para = new LinkedMultiValueMap<>();
		para.set("accountJSON", JSONObject.toJSON(account));
		String result = restTemplate.postForObject(url, para, String.class);
		JSONObject jsonObject;
		if (StringUtils.isNotEmpty(result)) {
			jsonObject = JSONObject.parseObject(result);
			Boolean isSuccess = jsonObject.getBoolean("isSuccess");
			return isSuccess;
		}

		return false;

	}

	public boolean usernameExist(String userName) {

		String url = Constants.RESTFUL_URL + "account/queryEmailExist";
		MultiValueMap<String, Object> para = new LinkedMultiValueMap<>();
		para.set("userName", userName);
		String result = restTemplate.postForObject(url, para, String.class);
		JSONObject jsonObject;
		if (StringUtils.isNotEmpty(result)) {
			jsonObject = JSONObject.parseObject(result);
			Boolean isExist = jsonObject.getBoolean("isExist");
			return isExist;
		}

		return false;

	}

}
